pepperstad.Structure = function(opts) {

    // Serializable fields
    this.poly = opts.poly || [];
    this.type = opts.type;
    this.name = opts.name;
    this.state = opts.state;

    // Transient dependencies and calculated fields
    var config = pepperstad.config;
    var buildingTypeDefinition = null;
    var color = null;
    var jobs = [];
    var graphics = null;
    var map = opts.map || null;
    var resourceLoader, storyConfig;
    if (opts.resourceLoader) {
        // resourceLoader is not required upon serialization
        resourceLoader = opts.resourceLoader;
        storyConfig = resourceLoader.get("story.config");
    }

    var self = this;

    this.addPolyPoint = function(coord) {
        this.poly.push(coord);
    };

    this.setColorFromType = function() {
        color = getBuildingDefinition().properties.color;
    };

    function getBuildingDefinition() {
        if (buildingTypeDefinition) return buildingTypeDefinition;

        var aBuildingDefinitions = resourceLoader.get("buildings");
        for (var i = 0; i < aBuildingDefinitions.length; i++) {
            buildingTypeDefinition = aBuildingDefinitions[i];
            if (buildingTypeDefinition.type === self.type) {
                return buildingTypeDefinition;
            }
        }
    }

    this.getJobs = function () {
        return jobs;
    };

    this.addJob = function(job) {
        jobs.push(job);
    };

    this.getAvailableJobsFromTypeDefinition = function() {
        return getBuildingDefinition().properties.jobs;
    };

    this.removeGraphics = function() {
        graphics.remove();
    };

    this.drawStructure = function(paper) {
        if (graphics) {
            // if redrawing, remove old svg element
            self.removeGraphics();
        }
        var poly = self.poly,
            str = "M",
            coord, i;
        self.setColorFromType();
        for (i = 0; i < poly.length; i++) {
            coord = poly[i];
            str += coord.x + "," + coord.y + "L";
        }
        str = str.substr(0, str.length - 1) + "z";
        graphics = paper.path(str).attr({
            stroke: config.stateColors[self.state],
            "stroke-width": config.structureStrokeWidth,
            "stroke-linecap": "round",
            fill: color,
            opacity: config.structureOpacity
        }).click(function clickHandler(evt) {
            map.handleStructureClicked(self);
                evt.stopPropagation();
            });
    };

    this.highlight = function(bHighlight) {
        graphics.attr({
            opacity: (bHighlight ? 1 : config.structureOpacity)
        });
    };

    this.getCapacity = function() {
        return Math.floor(graphics.getTotalLength() * storyConfig.capacityFactor);
    };

};

